package com.edu.marker.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLayoutChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.edu.marker.R;
import com.edu.marker.cache.EImageView;
import com.edu.marker.utils.CalculateUtil;

/**
 * 阅卷页面
 * */
public class MarkingActivity extends Activity implements OnClickListener,
		OnItemSelectedListener {
	private static final String TAG = "MarkingActivity----";
	private Button mPreBtn;
	private Button mNextBtn;
	// 索引
	private int index = 0;

	private EImageView mPaperImg;
	private Gallery gallery;
	private ImageAdapter mImageAdapter;
	private List<String> mUrls;

	private Bitmap mUseBitmap;
	private PopupWindow mPop;

	/** 图片相对与屏幕的坐标点x */
	private int mLeft;
	/** 图片相对与屏幕的坐标点y */
	private int mTop;
	/** 当前操作的试卷canvas */
	private Canvas mCanvas;
	/** 当前操作的画笔 */
	private Paint mPaint;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_marking);

		mPaperImg = (EImageView) findViewById(R.id.paper_img);
		mPreBtn = (Button) findViewById(R.id.pre_button);
		mNextBtn = (Button) findViewById(R.id.next_button);
		mPreBtn.setOnClickListener(this);
		mNextBtn.setOnClickListener(this);

		gallery = (Gallery) findViewById(R.id.gallery);

		mUrls = new ArrayList<String>();
		mUrls.add("http://comic.sinaimg.cn/2011/0824/U5237P1157DT20110824161051.jpg");
		mUrls.add("http://fujian.xabbs.com/forum/201109/02/160646nn9hjjiimixvkxhe.jpg");
		mUrls.add("http://img1.cache.netease.com/catchpic/A/A9/A9D98040B397C366AE93E67871346561.jpg");
		mUrls.add("http://new.aliyiyao.com/UpFiles/Image/2011/01/13/nc_129393721364387442.jpg");
		mUrls.add("http://pic.viewpics.cn/2011/07/03/naichaMMzhangzetianzuixinzhaopian/18.jpg");
		mUrls.add("http://i1.sinaimg.cn/ent/m/c/2010-01-18/U1819P28T3D2847679F326DT20100118115712.jpg");

		mImageAdapter = new ImageAdapter(this, mUrls);
		gallery.setAdapter(mImageAdapter);
		gallery.setOnItemSelectedListener(this);

		mPaperImg.addOnLayoutChangeListener(new OnLayoutChangeListener() {

			@Override
			public void onLayoutChange(View v, int left, int top, int right,
					int bottom, int oldLeft, int oldTop, int oldRight,
					int oldBottom) {
				int[] location = new int[2];
				mPaperImg.getLocationOnScreen(location);
				mLeft = location[0];
				mTop = location[1];
				Log.e("###", "mLeft :" + mLeft + " mTop :" + mTop);
			}
		});

		// 初始化画笔
		mPaint = new Paint(Paint.DITHER_FLAG);

		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeWidth(3);
		mPaint.setColor(Color.BLUE);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setAntiAlias(true);
	}

	// public void onWindowFocusChanged(boolean hasFocus) {
	// super.onWindowFocusChanged(hasFocus);
	// int[] location = new int[2];
	// mPaperImg.getLocationOnScreen(location);
	// mLeft = location[0];
	// mTop = location[1];
	// System.out.println("x:" + mLeft + "y:" + mTop);
	// }

	@Override
	public void onClick(View v) {

		int id = v.getId();
		switch (id) {
		case R.id.pre_button:
			index--;
			if (index < 0) {
				// 到最后一张
				index = mUrls.size() - 1;
			}
			gallery.setSelection(index);
			break;
		case R.id.next_button:
			index++;
			if (index >= mUrls.size()) {
				index = 0;
			}
			gallery.setSelection(index);
			break;
		case R.id.ok_btn:
			Log.e("###", "okBtn  onclick======== ");
			try {
				mCanvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
						R.drawable.right), 50, 50, null);
				mPaperImg.setImageBitmap(mUseBitmap);
				saveMyBitmap(new File("mnt/sdcard/ABC.png"));
				mPop.dismiss();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.cancel_btn:
			Log.e("###", "cancel_btn  onclick======== ");
			mPop.dismiss();
			break;

		default:
			break;
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Log.e(TAG, "onItemSelected = " + position);
		mPaperImg.setImageUri(mImageAdapter.getItem(position),
				R.drawable.ic_launcher);
		//
		int[] location = new int[2];
		mPaperImg.getLocationOnScreen(location);
		mLeft = location[0];
		mTop = location[1];
		Log.e(TAG, "x:" + mLeft + "y:" + mTop);
		//
		mUseBitmap = drawableToBitmap(mPaperImg.getDrawable());
		Log.e("###", "mUseBitmap.getHeight() = " + mUseBitmap.getHeight());
		Log.e("###", "mUseBitmap.getWidth() = " + mUseBitmap.getWidth());
		//
		// mUseBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
		//
		mCanvas = new Canvas(mUseBitmap);
		
		//针对每个图片画一个右下角的方形，测试使用==========================
//		int ivHeight =  mPaperImg.getHeight();
//		int ivWidth =  mPaperImg.getWidth();
//		Log.e(TAG, "ivHeight:" + ivHeight + " ivWidth:" + ivWidth);
//		Point point1 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
//				mUseBitmap.getWidth()-50, mUseBitmap.getHeight()-50,
//				ivHeight, ivWidth, mLeft, mTop);
//		Point point2 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
//				mUseBitmap.getWidth(), mUseBitmap.getHeight(),
//				ivHeight, ivWidth, mLeft, mTop);
//		// 320 * 450
//		Log.e("###", "point1 = "+point1.toString()+" point2 = "+point2.toString());
		mPaint.setColor(Color.RED);
//		//绘制右下角的矩形----测试用
//		mCanvas.drawRect(mUseBitmap.getWidth()-50, mUseBitmap.getHeight()-50, 
//				mUseBitmap.getWidth(), mUseBitmap.getHeight(), mPaint);
		//绘制左上角的矩形----测试用
		mCanvas.drawRect(0, 0, 50, 50, mPaint);

		mPaperImg.setImageBitmap(mUseBitmap);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		Log.e(TAG, "onNothingSelected ######");

	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.e("###", "onTouchEvent  ACTION_DOWN x = " + x + " y = " + y);
			int ivHeight =  mPaperImg.getHeight();
			int ivWidth =  mPaperImg.getWidth();
			Log.e(TAG, "ivHeight:" + ivHeight + " ivWidth:" + ivWidth);
			//右下角点击测试
//			Point point1 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
//					mUseBitmap.getWidth()-50, mUseBitmap.getHeight()-50,
//					ivHeight, ivWidth, mLeft, mTop);
//			Point point2 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
//					mUseBitmap.getWidth(), mUseBitmap.getHeight(),
//					ivHeight, ivWidth, mLeft, mTop);
			//左上角点击测试
			Point point1 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
			0, 0,
			ivHeight, ivWidth, mLeft, mTop);
			Point point2 = CalculateUtil.getRealPoint(mUseBitmap.getHeight(), mUseBitmap.getWidth(), 
			50, 50,
			ivHeight, ivWidth, mLeft, mTop);
			// 320 * 450
			Log.e("###", "point1 = "+point1.toString()+" point2 = "+point2.toString());
			
			boolean isNear = CalculateUtil.isPointNearRect( point1.x,
					point1.y, point2.x, point2.y, x, y);
			
//			boolean isNear = CalculateUtil.isPointNearRect(mLeft + 400,
//					mTop + 270, mLeft + 450, mTop + 320, x, y);
			//
			Log.e("###", "isPointNearRect  = " + isNear);
			if (isNear) {
				Toast.makeText(this, "点中====", Toast.LENGTH_SHORT).show();
				initPopMenu();
				mPop.showAtLocation(new View(this), Gravity.NO_GRAVITY, x, y);
//				mPop.showAtLocation(new View(this), Gravity.NO_GRAVITY,
//						mLeft + 450, mTop + 320);
			}
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			break;
		}

		return true;

	}

	/**
	 * 初始化评分对话框
	 */
	private void initPopMenu() {
		if (mPop == null) {
			View view = getLayoutInflater()
					.inflate(R.layout.score_dialog, null);
			mPop = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			mPop.setTouchable(true);
			mPop.setFocusable(true);
			mPop.setOutsideTouchable(true);
			view.setFocusableInTouchMode(true);
			Button okBtn = (Button) view.findViewById(R.id.ok_btn);
			Button cancelBtn = (Button) view.findViewById(R.id.cancel_btn);
			okBtn.setOnClickListener(this);
			cancelBtn.setOnClickListener(this);
			view.setOnKeyListener(new View.OnKeyListener() {

				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						if (null != mPop) {
							mPop.dismiss();
						}
					}
					return false;
				}
			});
			mPop.getContentView().setOnTouchListener(
					new View.OnTouchListener() {

						@Override
						public boolean onTouch(View v, MotionEvent event) {
							if (event.getAction() == MotionEvent.ACTION_UP) {
								if (null != mPop) {
									mPop.dismiss();
								}
							}
							return false;
						}
					});
		}
		if (mPop.isShowing()) {
			mPop.dismiss();
		}
	}

	private void closePop() {
		if (mPop != null) {
			mPop.dismiss();
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param file
	 * @throws IOException
	 */
	private void saveMyBitmap(File file) throws IOException {
		try {
			file.createNewFile();
			FileOutputStream fOut = null;
			fOut = new FileOutputStream(file);
			mUseBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

			fOut.flush();
			fOut.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * gallery Adapter
	 */
	public class ImageAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;
		private List<String> mList;

		class ViewHolder {
			EImageView itemImg;
		}

		public ImageAdapter(Context c, List<String> list) {
			context = c;
			mInflater = LayoutInflater.from(c);
			mList = list;
		}

		public int getCount() {
			return mList.size();
		}

		public String getItem(int position) {
			return mList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_gallery, null);
				holder = new ViewHolder();
				holder.itemImg = (EImageView) convertView
						.findViewById(R.id.gallery_item);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			String url = mList.get(position);
			holder.itemImg.setImageUri(url, R.drawable.ic_launcher);
			return convertView;
		}

	}
}
